let like = false
let collect = false
var Guseraccount = wx.getStorageSync('useraccount')
const app = getApp()
import {
    MyInofo,
    getUserLoveList,
    getonePost,
    getUserColletionList,
    getUserInfo,
    loginOut
} from '../../api/My/myinfo';
import {
    EditMyInfo
} from '../../api/My/myinfoEdit';
import {
    delMyColletionPost,
    delMyLovePost,
    delMyPost
} from '../../api/Post/post';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        navList: ['表白墙', '闲置', '喜欢', '收藏'],
        nav_type: 0,
        isFixed: false, //是否顶吸
        navTop: 0, //分类栏距离顶部的距离
        avatarUrl: null,
        user: {
            name: null,
            sex: '',
            phone: '',
            school: '',
            id: ''
        },
        count: {
            works: 0,
            like: 0
        },
        Wallpostlist: [],
        Sellpostlist: [],
        lovepostlist: [],
        collectionlist: [],
        postid: [0],
        sex: ["未知", "男", "女"],
        index: 0,
        like: "/img/空心.png",
        collect: "/img/收藏黑.png",
        head: '',
        show1: false,
        // 表单
        tip: false,
        warn: "",
        name: "",
        phone: "",
        school: "",
        pwd1: "",
        pwd2: "",
        show: false
    },

    // 分类栏切换
    changeType(e) {
        let {
            index
        } = e.currentTarget.dataset;
        if (this.data.nav_type == index || index == undefined) return;
        this.setData({
            nav_type: index
        })
    },
    // 点击隐藏和现实分类菜单
    more: function (e) {
        //  var postid=e.currentTarget.dataset.postid
        // console.log("1111",postid);
        // if(postid===this.data.postid){
        this.setData({
            show: true
        })
        //  }else{
        //     this.setData({
        //     show:false
        //     })
        //  }

    },
    // 点赞点击事件
    like() {
        if (like) {
            this.setData({
                like: "/img/空心.png"
            })
            like = false
        } else {
            this.setData({
                like: "/img/实心.png"
            })
            like = true
        }
    },
    getpostid: function (e) {
        var postid = e.currentTarget.dataset.postid
        this.setData({
            postid: postid
        })

        console.log(this.data.postid);
    },
    // 删除自己的帖子
    DelMypost: function () {
        var that = this
        wx.showModal({
            title: '确定删除',
            content: '',
            complete: (res) => {
                if (res.cancel) {
                    return;
                }

                if (res.confirm) {
                    console.log(this.data.postid);
                    // 点击确定后
                    delMyPost(
                        JSON.stringify([{
                            id: this.data.postid
                        }])
                    ).then(res => {
                        if (res.code == 200) {
                            wx.showToast({
                                title: '删除成功',
                                success: function () {
                                    that.checklogin()
                                }
                            })
                        } else {
                            wx.showToast({
                                title: '删除失败',
                            })
                        }
                    })
                }
            }
        })
    },
    //删除收藏
    DelMycolletion: function () {
        var that=this
        wx.showModal({
            title: '确定删除',
            content: '',
            complete: (res) => {
                if (res.cancel) {
                    return;
                }
                if (res.confirm) {
                    // 点击确定后
                    delMyColletionPost(
                        JSON.stringify({
                            PostId: this.data.postid,
                            UserId: this.data.user.id
                        })
                    ).then(res => {
                        if (res.code == 200) {
                            wx.showToast({
                                title: '删除成功',
                                success: function () {
                                    that.checklogin()
                                }
                            })
                        } else {
                            wx.showToast({
                                title: '删除失败',
                            })
                        }
                    })
                }
            }
        })
    },
    //删除喜欢
    DelMyLove: function () {
        var that=this
        wx.showModal({
            title: '确定删除',
            content: '',
            complete: (res) => {
                if (res.cancel) {
                    return;
                }
                if (res.confirm) {
                    // 点击确定后
                    //console.log("postid", this.data.postid);
                    delMyLovePost(
                        JSON.stringify({
                            PostId: this.data.postid,
                            UserId: this.data.user.id
                        })
                    ).then(res => {
                        if (res.code == 200) {
                            wx.showToast({
                                title: '删除成功',
                                success: function () {
                                    that.checklogin()
                                }
                            })
                        } else {
                            wx.showToast({
                                title: '删除失败',
                            })
                        }
                    })
                }
            }
        })
    },
    // 修改个人信息
    onLoad: function (options) {},
    //点击我显示底部弹出框
    clickme: function () {
        this.showModal();
    },
    changename: function () {
        this.showModalname();

    },
    //显示对话框
    showModal: function () {
        // 显示遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({
            animationData: animation.export(),
            showModalStatus: true
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export()
            })
        }.bind(this), 200)
    },
    //隐藏对话框
    hideModal: function () {
        // 隐藏遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({
            animationData: animation.export(),
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export(),
                showModalStatus: false
            })
        }.bind(this), 200)
    },
    onChooseAvatar: function (e) {
        //但是微信小程序只返回一个avatar 不区分上传方式
        const {
            avatarUrl
        } = e.detail
        this.setData({
            avatarUrl: avatarUrl
        })
        var that = this
        //将头像上传服务器 
        wx.uploadFile({
            filePath: avatarUrl,
            name: 'file',
            url: 'https://22062002.xyz:8086/biz/buFile/uploadAliyun',
            success: function (res) {
                console.log("返回", res)
                //json处理
                const data = JSON.parse(res.data);
                console.log("头像地址", data.data);
                var useravatar = data.data
                //修改个人信息里面的头像 其他不变
                EditMyInfo({
                    "avatar": useravatar,
                    "account": that.data.user.name,
                    "sex": that.data.user.sex,
                    "college": that.data.user.school,
                    "phone": that.data.user.phone,
                    "type": 0,
                    "password": "",
                    "confirmPassword": "",
                    "id": that.data.user.id
                }).then((res) => {
                    if (res.code == 200) {
                        wx.showToast({
                            title: '修改成功',
                            icon: 'success'
                        });
                    } else {
                        wx.showToast({
                            title: '修改失败',
                            icon: 'none'
                        });
                        console.log(res);
                    }
                })
            },
            fail: function (e) {
                console.error('上传失败', e);
                wx.showToast({
                    title: '上传失败',
                    icon: 'none'
                })
            },
            complete: function () {
                wx.hideToast(); //隐藏Toast
            }
        })
    },


    // 修改昵称
    changename: function () {
        var s = this.data.show1
        this.setData({
            show1: !s,
            warn: ""
        })
    },
    // 选择性别
    bindPickerChange: function (e) {
        this.setData({
            index: e.detail.value
        })
        console.log("index", this.data.index);
        if (this.data.index == 1) {
            EditMyInfo({
                "avatar": this.data.avatarUrl,
                "account": this.data.user.name,
                "sex": "男",
                "college": this.data.user.school,
                "phone": this.data.user.phone,
                "type": 0,
                "password": "",
                "confirmPassword": "",
                "id": this.data.user.id
            }).then((res) => {
                if (res.code == 200) {
                    wx.showToast({
                        title: '修改成功',
                        icon: 'success'
                    });
                } else {
                    wx.showToast({
                        title: '修改失败',
                        icon: 'none'
                    });
                    console.log(res);
                }
            })
        } else if (this.data.index == 2) {
            EditMyInfo({
                "avatar": this.data.avatarUrl,
                "account": this.data.user.name,
                "sex": "女",
                "college": this.data.user.school,
                "phone": this.data.user.phone,
                "type": 0,
                "password": "",
                "confirmPassword": "",
                "id": this.data.user.id
            }).then((res) => {
                if (res.code == 200) {
                    wx.showToast({
                        title: '修改成功',
                        icon: 'success'
                    });
                } else {
                    wx.showToast({
                        title: '修改失败',
                        icon: 'none'
                    });
                    console.log(res);
                }
            })
        } else {
            //改为未知
            EditMyInfo({
                "avatar": this.data.avatarUrl,
                "account": this.data.user.name,
                "sex": "未知",
                "college": this.data.user.school,
                "phone": this.data.user.phone,
                "type": 0,
                "password": "",
                "confirmPassword": "",
                "id": this.data.user.id
            }).then((res) => {
                if (res.code == 200) {
                    wx.showToast({
                        title: '修改成功',
                        icon: 'success'
                    });
                } else {
                    wx.showToast({
                        title: '修改失败',
                        icon: 'none'
                    });
                    console.log(res);
                }
            })
        }
    },
    // 修改手机号
    changephone: function () {
        var s = this.data.show2
        this.setData({
            show2: !s,
            warn: ""
        })
    },
    // 修改密码
    changepwd: function () {
        var s = this.data.show4
        this.setData({
            show4: !s,
            warn: ""
        })
    },
    changeschool: function () {
        var s = this.data.show3
        this.setData({
            show3: !s,
            warn: ""
        })
    },
    checkname(e) {
        const name = e.detail.value;
        if (name.length == 0) {
            this.setData({
                warn: "请输入昵称！",
                tip: true,
            })
        } else {
            this.setData({
                warn: "",
                tip: false,
            })
        }
    },
    checkphone(e) {
        const phone = e.detail.value;
        if (phone.length == 0 || phone.length < 11) {
            this.setData({
                warn: "请输入正确的手机号！",
                tip: true,
            })
        } else {
            this.setData({
                warn: "",
                tip: false,
            })
        }
    },
    checkpwd(e) {
        const pwd1 = e.detail.value;
        const pwd2 = e.detail.value;
        if (pwd1.length < 6) {
            this.setData({
                warn: "密码长度不能少于6位！",
                tip: true,
            })
        } else {
            this.setData({
                warn: "",
                tip: false,
            })
        }
    },
    //昵称
    formSubmit1: function (e) {
        var that = this
        let {
            name
        } = e.detail.value;
        EditMyInfo({
            "avatar": that.data.avatarUrl,
            "account": name,
            "sex": that.data.user.sex,
            "college": that.data.user.school,
            "phone": that.data.user.phone,
            "type": 0,
            "password": "",
            "confirmPassword": "",
            "id": that.data.user.id
        }).then((res) => {
            if (res.code == 200) {
                wx.showToast({
                    title: '修改成功',
                    icon: 'success',
                    success: function () {
                        that.checklogin()
                    }
                });
            } else {
                wx.showToast({
                    title: '修改失败',
                    icon: 'none'
                });
                console.log(res);
            }
        })
    },
    //手机号
    formSubmit2: function (e) {
        let that = this
        let {
            phone
        } = e.detail.value;
        EditMyInfo({
            "avatar": that.data.avatarUrl,
            "account": that.data.user.name,
            "sex": that.data.user.sex,
            "college": that.data.user.school,
            "phone": phone,
            "type": 0,
            "password": "",
            "confirmPassword": "",
            "id": that.data.user.id
        }).then((res) => {
            if (res.code == 200) {
                wx.showToast({
                    title: '修改成功',
                    icon: 'success',
                    success: function () {
                        that.checklogin()
                    }
                });
            } else if (res.code == 400) {
                wx.showToast({
                    title: res.msg,
                    icon: 'none'
                });
                console.log(res);
            }
        })
    },
    //学校
    formSubmit3: function (e) {
        let that = this
        let {
            school
        } = e.detail.value;
        EditMyInfo({
            "avatar": that.data.avatarUrl,
            "account": that.data.user.name,
            "sex": that.data.user.sex,
            "college": school,
            "phone": that.data.user.phone,
            "type": 0,
            "password": "",
            "confirmPassword": "",
            "id": that.data.user.id
        }).then((res) => {
            if (res.code == 200) {
                wx.showToast({
                    title: '修改成功',
                    icon: 'success',
                    success: function () {
                        that.checklogin()
                    }
                });
            } else if (res.code == 400) {
                wx.showToast({
                    title: res.msg,
                    icon: 'none'
                });
                console.log(res);
            }
        })
    },
    //密码
    formSubmit4: function (e) {
        let that = this
        let {
            pwd1,
            pwd2
        } = e.detail.value;
        if (!pwd1 || !pwd2) {
            wx.showToast({
                title: '请修改密码',
                icon: 'none'
            })
        } else if (pwd2 != pwd1) {
            this.setData({
                warn: "两次密码不一致！",
                tip: true,
            })
        } else {
            EditMyInfo({
                "avatar": that.data.avatarUrl,
                "account": that.data.user.name,
                "sex": that.data.user.sex,
                "college": that.data.user.school,
                "phone": that.data.user.phone,
                "type": 0,
                "password": pwd1,
                "confirmPassword": pwd2,
                "id": that.data.user.id
            }).then((res) => {
                if (res.code == 200) {
                    wx.showToast({
                        title: '修改成功',
                        icon: 'success',
                        success: function () {
                            that.checklogin()
                        }
                    });
                } else if (res.code == 400) {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                    console.log(res);
                }
            })
        }
    },
    //判断是否登录 登录查询并显示用户信息
    checklogin() {
        //登录
        var islogin = wx.getStorageSync('isLoggedIn')
        console.log("个人页面全局", app.globalData.isLoggedIn);
        if (islogin) {
            var userid = wx.getStorageSync('userid')
            console.log("userid", userid);
            MyInofo(userid).then(res => {
                console.log(res.data);
                if (res.data != null) {
                    this.setData({
                        user: {
                            name: res.data.account,
                            sex: res.data.sex,
                            phone: res.data.phone,
                            school: res.data.college,
                            id: res.data.userId
                        },
                        avatarUrl: res.data.avatar
                    })
                    // console.log("school",this.data.user.school);
                    if (this.data.user.sex == "男") {
                        this.setData({
                            index: 1
                        })
                    } else if (this.data.user.sex == "女") {
                        this.setData({
                            index: 2
                        })
                    } else {
                        this.setData({
                            index: 0
                        })
                    }
                    // console.log("avatarUrl",this.data.avatarUrl);

                    var userID = wx.getStorageSync('userid')
                    getUserInfo(userID).then(res => {
                        if (res.data != null) {
                            var works = res.data
                            // console.log("全部", res.data);
                            var love = 0
                            //表白墙 闲置
                            var wallpostlist = []
                            var sellpostlist = []
                            works.forEach(function (item, index) {
                                love = item.total + love
                                // var newItem = {
                                //     ...item, // 使用解构赋值来复制原始对象的所有属性
                                //     isImageVisible: false // 添加新的属性，初始化为false
                                // }
                                if (item.cateId == 3 || item.cateId == 5) {
                                    sellpostlist.push(item);
                                } else {
                                    wallpostlist.push(item);
                                }
                            })
                            this.setData({
                                Wallpostlist: wallpostlist,
                                Sellpostlist: sellpostlist
                            })
                            // console.log("Wallpostlist", this.data.Wallpostlist);
                            console.log("Sellpostlist", this.data.Sellpostlist);
                            this.setData({
                                count: {
                                    works: res.data.length,
                                    like: love
                                }
                            })

                        } else {
                            console.log("表白墙/闲置数据为空");
                        }
                    })
                } else {
                    console.log("user数据为空");
                }
            }).catch(err => {
                console.log("失败", err);
            })
            //喜欢
            var userID = wx.getStorageSync('userid')
            getUserLoveList(userID).then(res => {
                // console.log("喜欢", res.data);
                if (res.data != null) {
                    var lovelist = res.data
                    var allPromise = lovelist.map(function (item, index) {
                        return getonePost(item.postId).then(res => {
                            return res.data
                        })
                    });
                    Promise.all(allPromise).then(allResults => {
                        this.setData({
                            lovepostlist: allResults
                        })
                        // console.log("喜欢帖子", this.data.lovepostlist);
                    })
                } else {
                    console.log("喜欢帖子数据为空");
                }
            }).catch(err => {

                console.log("失败", err);
            })
            //收藏
            getUserColletionList(userID).then(res => {
                console.log("收藏", res.data);
                if (res.data != null) {
                    var collectionlist = res.data
                    var allPromise = collectionlist.map(function (item, index) {
                        return getonePost(item.postId).then(res => {
                            return res.data
                        })
                    });
                    Promise.all(allPromise).then(allResults => {
                        this.setData({
                            collectionlist: allResults
                        })
                        // console.log("收藏帖子", allResults);
                    })
                } else {
                    console.log("收藏帖子数据为空");
                }
            }).catch(err => {

                console.log("失败", err);
            })
        } else {
            console.log("未登录");
        }
    },
    //退出登录
    loginout() {
        var token = wx.getStorageSync('token')
        loginOut(token).then(res => {
            if (res.code == 200) {
                this.setData({
                    showModalStatus: false,
                    //恢复默认值
                    user: {
                        name: null,
                        sex: '',
                        phone: '',
                        school: '',
                        id: ''
                    },
                    count: [{
                        works: 0,
                        like: 0
                    }],
                    Wallpostlist: [],
                    Sellpostlist: [],
                    lovepostlist: [],
                    collectionlist: [],
                })
                wx.showToast({
                    title: '退出登陆成功',
                    success: function () {
                        //登陆状态改为false
                        app.globalData.isLoggedIn = false;
                        console.log("登出", app.globalData.isLoggedIn);
                        //清空缓存
                        wx.clearStorageSync();
                        //清除请求头的token
                        wx.navigateTo({
                            url: '/pages/login/login'
                        });
                    }
                })
            }
        })
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log("触发load", app.globalData.isLoggedIn);
        this.checklogin()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        //获取节点距离顶部的距离
        wx.createSelectorQuery().select("#nav").boundingClientRect((rect) => {
            if (rect && rect.top) {
                this.setData({
                    navTop: parseInt(rect.top)
                })
            }
        }).exec()
    },
    onPageScroll(e) {
        let scrollTop = parseInt(e.scrollTop),
            isFixed = scrollTop >= this.data.navTop;
        if (this.data.isFixed !== isFixed) {
            this.setData({
                isFixed
            })
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 4
            })
        }
        this.checklogin()
        console.log("触发show", app.globalData.isLoggedIn);
        if (app.globalData.isLoggedIn == false) {
            this.setData({
                //恢复默认值
                user: {
                    name: null,
                    sex: null,
                    phone: null,
                    school: null,
                    id: null
                },
                postlist: []
            })
        } else {
            console.log("进来了", app.globalData.token);
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {


    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})